package com.dhgate.amazon.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;


public class BaseDao{

	protected boolean addObjects(Object objs)throws Exception{
		Session session = HibernateSessionFactory.getSession();
		Transaction t = null;
		try {
			t = session.beginTransaction();
			t.begin();
			List<Object> objst=(List<Object>)objs;
			for(Object obj:objst){
				session.save(obj);
			}
			t.commit();
			return true;
		} catch (Exception e) {
			t.rollback();
			throw e;
		}finally{
			if(session != null) {
				session.close();
			}
		}
	}
	
	/**
	 * 添加一条数据
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	protected boolean addObject(Object obj) throws Exception{
		Session session = HibernateSessionFactory.getSession();
		Transaction t = null;
		try {
			t = session.beginTransaction();
			t.begin();
			session.save(obj);
			t.commit();
			return true;
		} catch (Exception e) {
			t.rollback();
			throw e;
		}finally{
			if(session != null) {
				session.close();
			}
		}
	}
	
	/**
	 * 根据sql语句获得需要的所有的结果
	 * @param sql
	 * @return
	 * @throws Exception
	 */
	protected List getAllObjectsBySql(String sql) throws Exception {
		Session session = HibernateSessionFactory.getSession();
		try {
			Query query = session.createSQLQuery(sql);
			return query.list();
		} catch (Exception e) {
			throw e;
		}finally{
			if(session != null) {
				session.close();
			}
		}
	}
	
	/**
	 * 根据hql获得需要的所有的结果
	 * @param hql
	 * @return
	 * @throws Exception
	 */
	protected List getAllObjectsByHql(String hql) throws Exception{
		Session session = HibernateSessionFactory.getSession();
		try {
			Query query = session.createQuery(hql);
			return query.list();
		} catch (Exception e) {
			throw e;
		}finally{
			if(session != null) {
				session.close();
			}
		}
	}
}
